from flask import Flask, redirect, url_for, send_from_directory
from flask_sqlalchemy import SQLAlchemy
import os
import logging

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from models import db
# 创建Flask应用实例
server = Flask(__name__, template_folder='templates')  # 确保指定模板文件夹

# 配置数据库
db_path = os.path.abspath('instance/mis.db')
server.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
server.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
server.config['SECRET_KEY'] = 'your-secret-key-for-sessions'  # 添加密钥用于会话

# print("server p 20 数据库连接：", server.config["SQLALCHEMY_DATABASE_URI"])



# 确保实例文件夹存在
os.makedirs(os.path.dirname(db_path), exist_ok=True)

# 只注册一次
db.init_app(server)
migrate = Migrate(server, db)

# 添加数据库表创建（仅当数据库文件不存在时执行）
if not os.path.exists(db_path):
    with server.app_context():
        try:
            db.create_all()
            print(f"Database created at: {db_path}")  # 添加调试信息
        except Exception as e:
            print(f"Database creation error: {str(e)}")  # 输出具体错误信息


# # 确保实例文件夹存在
# os.makedirs(os.path.dirname(db_path), exist_ok=True)

#生成二维码
from modules.equipment.QRcode import bp as equipment_qrcode_bp
server.register_blueprint(equipment_qrcode_bp, url_prefix='/equipment')



# --- 添加根路由 ---
@server.route('/')
def index():
    
    return redirect('/dash/')

@server.route('/login')
def login_redirect():
    # 重定向到Dash应用内部的登录页面
    return redirect('/dash/login')

# 添加初始化管理员命令
@server.cli.command("create-admin")
def create_admin():
    """创建初始管理员账户"""
    from models import User
    from werkzeug.security import generate_password_hash
    
    with server.app_context():
        if User.query.filter_by(role='admin').first():
            print("管理员账户已存在")
            return
        
        username = input("请输入管理员用户名: ")
        password = input("请输入管理员密码: ")
        
        admin = User(
            username=username,
            password=generate_password_hash(password),
            role='admin',
            is_active=True
        )
        db.session.add(admin)
        db.session.commit()
        print("管理员账户创建成功")

# 添加静态文件路由
@server.route('/static/css/<path:filename>')
def serve_css(filename):
    # print(f"请求CSS文件: {filename}")  # 添加调试输出
    css_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static/css')
    # print(f"CSS目录路径: {css_path}")  # 添加调试输出
    return send_from_directory(css_path, filename)

#
# 添加图标文件路由
@server.route('/static/icon/<path:filename>')
def serve_icon(filename):
    return send_from_directory(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static/icon'), filename)

# 添加地图文件路由
@server.route('/static/map/<path:filename>')
def serve_map(filename):
    return send_from_directory(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static/map'), filename)

# 在创建Flask应用后添加以下代码
@server.after_request
def add_security_headers(response):
    # 添加内容安全策略头，允许百度地图和地理位置API
    response.headers['Content-Security-Policy'] = "default-src 'self' data: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.baidu.com; style-src 'self' 'unsafe-inline' https://*.baidu.com; img-src 'self' data: https://*.baidu.com; connect-src 'self' https://*.baidu.com; frame-src 'self' https://*.baidu.com; worker-src 'self' blob:;"
    # 添加权限策略头，允许cookie访问
    response.headers['Permissions-Policy'] = "camera=(), microphone=(), geolocation=(), interest-cohort=()"
    
    return response

from models import User

# 初始化 Flask-Login
login_manager = LoginManager()
login_manager.init_app(server)
login_manager.login_view = 'login_redirect' # 这里的'login'要和你的登录路由一致

# 添加 user_loader 回调
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

if __name__ != '__main__':
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.WARNING)